package cl.foursoft.sirvicod.dao.implementacion.postgresql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import cl.foursoft.sirvicod.dao.implementacion.DBBase;
import cl.foursoft.sirvicod.dao.interfaces.IVisita;
import cl.foursoft.sirvicod.dao.transferObject.VisitaTO;
import cl.foursoft.sirvicod.util.UtilLog;

public class VisitaDB extends DBBase implements IVisita {

	public VisitaDB(Connection connection){
		this.conn = connection;
	}
	
	
	@Override
	public int guardarVisita(VisitaTO visitaTO) {

		int resp = -1;
		
		PreparedStatement pstmt = null;

		String query = 	" INSERT INTO visita " +
						" ( " +
							" numero_depto, " +
							" rut " +
						" ) " +
						" VALUES (?, ?);";
		
		try
		{
			pstmt = conn.prepareStatement(query);
			pstmt.setInt(1, visitaTO.getDeptoTO().getNumeroDepto());
			pstmt.setString(2, visitaTO.getPersonaTO().getRut());
			resp = pstmt.executeUpdate();
			pstmt.close();
		}

		catch (SQLException sqle){
			UtilLog.registrar(sqle);
		}
		catch (Exception ex) {
			UtilLog.registrar(ex);
		}
		
		finally{
			if (pstmt != null) {
				try{
					pstmt.close();					
				} 
				catch (SQLException e) {
					UtilLog.registrar(e); 
					e.printStackTrace();
				}
			}
		}	
				
		return resp;
	}

	
	@Override
	public List<VisitaTO> obtenerVisitaPorDepto(int numeroDepto) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public int obtenerSiguienteID(){
		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		int resp = -1;
		String query = "SELECT nextval('visita_id_visita_seq') as NEXTVAL";
		
		try
		{						
			pstmt = conn.prepareStatement(query);
						
			rs = pstmt.executeQuery();
			
			if(rs.next())
				resp = rs.getInt("NEXTVAL");
			
			pstmt.close();
			
		}
		catch (SQLException sqle) {
			UtilLog.registrar(sqle);
		}catch (Exception ex) {
			UtilLog.registrar(ex);
		}  
		finally{
			if (pstmt != null) {
		          try {
		               pstmt.close();
		               
		          } catch (SQLException e) {
		        	  UtilLog.registrar(e);  
		        	  e.printStackTrace();
		          }
			}
		}		
		return resp;
	}


	@Override
	public List<VisitaTO> buscarVisitasAutorizadasPorDepto(int depto) {
		// TODO Auto-generated method stub
		return null;
	}
}
